<template>
  <div class="app-container">
    <aside class="flex">
      <span class="flex-1">数据表管理</span>
      <el-button type="primary" icon="el-icon-plus" @click="changeTable(addTableIndex)">新增表格</el-button>
    </aside>
    <el-container>
      <el-main>
        <el-container>
          <!--数据表列表-->
          <el-aside style="width: 150px;padding: 0;">
            <el-menu :default-active="activeTable" class="el-menu-vertical-demo" @select="changeTable" @close="handleClose">
              <el-menu-item v-for="(item, index) of tables" :key="'table' + index" :index="item.name">
                <span slot="title">{{ item.title }}</span>
              </el-menu-item>
            </el-menu>
          </el-aside>
          <el-container>
            <div style="margin: 0 20px;width: 100%;">
              <aside>
                <el-form inline class="mt-20 flex">
                  <el-form-item label="表名："><el-input v-model="table.name" placeholder="仅限英文" /></el-form-item>
                  <el-form-item label="中文名:"><el-input v-model="table.title" placeholdeer="备注名称" /></el-form-item>
                  <el-form-item v-if="table.id === 0"><el-button type="danger" icon="el-icon-position" @click="createTable">创建</el-button></el-form-item>
                  <el-form-item v-if="table.id !== 0"><el-button type="danger" icon="el-icon-position" @click="updateTable">保存</el-button></el-form-item>
                  <el-form-item class="flex-1" />
                  <el-form-item v-if="table.id > 0"><el-button type="danger" icon="el-icon-delete" @click="deleteTable">删除表格</el-button></el-form-item>
                  <el-form-item><el-button type="primary" icon="el-icon-plus" @click="addColumn(0)">新增字段</el-button></el-form-item>
                </el-form>
              </aside>
              <el-table :data="table.columns" height="60vh">
                <el-table-column label="名称">
                  <template slot-scope="{row}">
                    <el-input v-model="row.name" />
                  </template>
                </el-table-column>
                <el-table-column label="标题">
                  <template slot-scope="{row}">
                    <el-input v-model="row.title" />
                  </template>
                </el-table-column>
                <el-table-column label="类型">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.type">
                      <el-option v-for="(item, index) of types" :key="scope.$index + '-' + index" :label="item[1]" :value="item[0]">{{ item[1] }}</el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="长度">
                  <template slot-scope="{row}">
                    <el-input v-model="row.length" />
                  </template>
                </el-table-column>
                <el-table-column label="小数位">
                  <template slot-scope="{row}">
                    <el-input v-model="row.floatnum" />
                  </template>
                </el-table-column>
                <el-table-column label="排序">
                  <template slot-scope="{row}">
                    <el-input v-model="row.sort" @change="reSort" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteColumn(scope.$index)">删除</el-button>
                    <el-button type="primary" size="mini" icon="el-icon-plus" @click="addColumn(scope.$index + 1)">插入</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-container>
        </el-container>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import table from '@/api/table'
export default {
  name: 'DBIndex',
  components: {},
  data() {
    return {
      activeTable: '',
      addTableIndex: 'new-table',
      tables: [
      ],
      table: {
        id: 0,
        title: '',
        name: '',
        columns: []
      },
      types: [['integer', '整数'], ['string', '字符串'], ['textarea', '段落'], ['date', '日期'], ['datetime', '时间'], ['file', '文件'], ['text', '文章']]
    }
  },
  created() {
    // this.addColumn()
    this.getTables()
  },
  methods: {
    /**
     * 切换表格
     * @param index
     */
    changeTable(index) {
      console.log(index)
      if (index === this.activeTable) {
        return
      }
      this.activeTable = index
      if (this.addTableIndex === index) {
        this.table = {
          id: 0,
          title: '',
          name: '',
          columns: []
        }
        this.addColumn()
      } else {
        for (const table of this.tables) {
          if (table.name === index) {
            this.table.name = table.name
            this.table.title = table.title
            this.table.id = table.id
            this.getColumns(table.id)
          }
        }
      }
    },
    handleClose() {
    },
    /**
     * 获取表格
     */
    getTables() {
      table.search().then(res => {
        this.tables = res.data
      })
    },
    /**
     * 获取表格字段
     * @param id
     */
    getColumns(id) {
      table.detail(id).then(res => {
        this.table.columns = res.data
      })
    },
    addColumn(index) {
      const empty = { id: 0, name: '', type: '', length: 0, title: '', floatnum: 0 }
      if (index === 0) {
        this.table.columns.push(empty)
      } else {
        this.table.columns.splice(index - 1, 0, empty)
      }
    },
    /**
     * 删除表格
     */
    deleteTable() {
      this.$confirm('删除表格将同时删除数据，确定删除吗').then(res => {
        // 再次确认
        this.$confirm('数据将被彻底删除，请再次确认').then(res => {
          table.delete(this.table.id).then(res => {
            // 删除表格成功
            const len = this.tables.length
            for (let i = 0; i < len; i++) {
              if (this.tables[i].id === this.table.id) {
                this.tables.splice(i, 1)
                break
              }
            }
            this.table.id = 0
            this.table.name = ''
            this.table.title = ''
            this.activeTable = this.addTableIndex
            this.table.columns = []
          }).catch(() => {})
        })
      })
    },
    /**
     * 删除字段
     * @param index
     * @returns {*[]}
     */
    deleteColumn(index) {
      console.log(index)
      const column = this.table.columns[index]
      if (this.activeTable === this.addTableIndex || column.id === 0) {
        return this.table.columns.splice(index, 1)
      }
      this.$confirm('删除【' + column.title + '】字段，本字段的数据也会被删除，确定吗').then(res => {
        this.$confirm('请再次确认').then(res => {
          table.deleteColumn(column.id).then(res => {
            // 删除成功
            this.table.columns.splice(index, 1)
          })
        }).catch(() => {})
      }).catch(() => {})
    },
    /**
     * 创建表格
     */
    createTable() {
      table.create(this.table.title, this.table.name, this.table.columns).then(res => {
        this.$message.success('创建成功')
        const index = 'table' + this.tables.length
        this.getTables()
        // 切换到表格编辑状态
        setTimeout(() => {
          this.changeTable(index)
        }, 2000)
      }).catch(res => {})
    },
    updateTable() {
      table.update(this.table).then(res => {
        this.$message.success('保存成功')
        this.getTables()
      })
    },
    reSort() {
      this.table.columns = this.table.columns.sort(function(a, b) {
        return a.sort - b.sort
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
